import {ReactElement, useEffect, useMemo, useState, FC, useRef} from 'react';
import ImagePicker from 'react-native-image-crop-picker';
import Spinner from 'react-native-loading-spinner-overlay';
import NfcManager, {NfcTech} from 'react-native-nfc-manager';
import MasonryList from '@react-native-seoul/masonry-list';
//@ts-ignore
import ActionSheet from 'react-native-actionsheet';
import {
  Image,
  ScrollView,
  StyleProp,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import {getDetails, getTypes} from 'services';
interface Furniture {
  img_url: string;
}

export default ({size}) => {
  const [tags, setTags] = useState<
    {
      sort: number;
      name: string;
      id: string;
    }[]
  >([]);
  useEffect(() => {
    getTypes().then(data => {
      setTags(data);
    });
  }, []);
  const ActionSheetRef = useRef();
  const [visible, setVisible] = useState(false);
  const [images, setImages] = useState<{img_url: string}[]>([]);
  const [active, setInactive] = useState(0);
  useEffect(() => {
    if (tags.length > 0) {
      getDetails(tags[active].id).then(data => {
        setImages(data);
      });
    }
  }, [active, tags]);
  const onPress = (index: number) => {
    setInactive(index);
  };
  async function readNdef(image: string, type: number) {
    try {
      await NfcManager.requestTechnology(NfcTech.IsoDep);
      const tag = await NfcManager.getTag();
      if (tag) {
        //@ts-ignore
        NfcManager.sendPicture(image, type);
      }
    } catch (e) {
      console.log('error:' + e);
    } finally {
      setVisible(false);
      NfcManager.cancelTechnologyRequest();
    }
  }
  const onClick = (data: {img_url: string}, index?: number) => {
    let current;
    if (index >= 0) {
      current = ['360x240', '416x240', '800x480'][index].split('x');
    }
    ImagePicker.openCropper({
      mediaType: 'photo',
      width: index >= 0 ? +current[1] : size[1],
      height: index >= 0 ? +current[0] : size[0],
      cropping: true,
      showCropGuidelines: false,
      freeStyleCropEnabled: false,
      hideBottomControls: true,
      // cropperToolbarTitle: data.size + '寸',
      cropperToolbarTitle: '图片裁剪',
      path: data.img_url,
      // path:"file:///data/user/0/com.awesomeproject/files/1712996572027.jpeg"
    }).then(image => {
      setVisible(true);
      readNdef(image.path as string, 1);
    });
  };
  const indexRef = useRef<Furniture>();
  const FurnitureCard: FC<{
    item: Furniture;
    style: StyleProp<ViewStyle>;
    index: number;
  }> = ({item, index, style}) => {
    const randomBool = useMemo(() => Math.random() < 0.5, []);

    return (
      <TouchableOpacity
        onPress={() => {
          if (size) {
            onClick(item);
          } else {
            indexRef.current = item;
            ActionSheetRef.current?.show();
          }
          // ;
        }}
        key={index}
        style={[{marginTop: 12, flex: 1}, style]}>
        <Image
          source={{uri: item.img_url}}
          style={{
            height: randomBool ? 200 : 360,
            alignSelf: 'stretch',
            borderRadius: 4,
          }}
          resizeMode="cover"
        />
      </TouchableOpacity>
    );
  };
  const renderItem = ({
    item,
    i,
  }: {
    item: Furniture;
    i: number;
  }): ReactElement => {
    return (
      <FurnitureCard
        item={item}
        index={i}
        style={{marginLeft: i % 2 === 0 ? 0 : 12}}
      />
    );
  };
  return (
    <>
      <Spinner
        visible={visible}
        color="#409EFF"
        textContent="同步中,请稍候"
        textStyle={{
          fontSize: 14,
          color: '#409EFF',
        }}></Spinner>
      <ScrollView
        contentContainerStyle={{
          height: 44,
          marginVertical: 7,
          alignItems: 'center',
          paddingHorizontal: 12,
          columnGap: 0,
        }}
        horizontal
        style={{flexDirection: 'row', flexGrow: 0}}>
        {tags.map((item, index) => {
          return (
            <TouchableOpacity
              key={index}
              style={[styles.primary, active === index ? styles.active : null]}
              onPress={() => {
                onPress(index);
              }}>
              <View key={item.id}>
                <Text style={[active === index ? styles.active_text : null]}>
                  {item.name}
                </Text>
              </View>
            </TouchableOpacity>
          );
        })}
      </ScrollView>
      <MasonryList
        keyExtractor={(_: Furniture, index): string => index + ''}
        ListHeaderComponent={<View />}
        contentContainerStyle={{
          paddingHorizontal: 12,
          alignSelf: 'stretch',
          paddingBottom: 12,
        }}
        numColumns={2}
        data={images}
        renderItem={renderItem}
      />
      <ActionSheet
        ref={ActionSheetRef}
        title="请选择尺寸"
        options={['360x240', '416x240', '800x480', '取消']}
        cancelButtonIndex={3}
        destructiveButtonIndex={0}
        onPress={index => {
          /* do something */
          onClick(indexRef.current, index);
        }}
      />
    </>
  );
};
const styles = StyleSheet.create({
  active: {
    backgroundColor: 'rgba(0, 122, 255, 0.08)',
  },
  primary: {
    paddingHorizontal: 13,
    paddingVertical: 5,
    backgroundColor: 'rgba(111, 111, 111, 0.08)',
    height: 30,
    marginRight: 11,
  },
  active_text: {
    color: 'rgba(0, 122, 255, 1)',
  },
});
